import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import {ElMessage} from "element-plus";

const routes = [
  {
    path: '/',
    name: 'home',
    component: HomeView,
    redirect:'/user',
    children:[
      {path: '/user', component: () => import('../views/user/UserView.vue')},
      {path: '/vehicle', component: () => import('../views/vehicle/VehicleView.vue')},
      {path: '/geofence', component: () => import('../views/geofence/GeofenceView.vue')},
      {path: '/geofenceMap', component: () => import('../views/geofence/GeofenceMapView.vue')},
      {path: '/application', component: () => import('../views/schedule/ApplicationView.vue')},
      {path: '/audit', component: () => import('../views/schedule/AuditView.vue')},
      {path: '/distribute', component: () => import('../views/schedule/DistributeView.vue')},
      {path: '/dict', component: () => import('../views/dictionary/DictView.vue')},
      {path: '/dictOption', component: () => import('../views/dictionary/DictOptionView.vue')}
    ]
  },
  {
    path: '/login',
    component: () => import('../views/LoginView.vue')
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})
//路由切换之前先判断localStorage中是否有用户信息，没有信息就尝试进行访问登录页面
//to要进去的路由目标，from当前的路径对象，next函数中进入下一个路由
router.beforeEach((to,from,next)=>{
  //从本地存储中获取用户信息
  let user = localStorage.user;
  //判断当前用户是否在登录页面并且不在默认页面中，不在登录页面重定向到登录页面，并提示登录
  if(to.path!="/login" && !user && to.path!="/"){
    next({
      path:'/login',query:{redirect:to.fullPath}
    },
        ElMessage.error("请登录"))
  }else {
    //允许路由切换
    next();
  }
})

export default router
